from numpy import sort
import wx
import os

def addCaption(self,control,captiontxt):
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        parent = control.GetParent()

        caption = wx.StaticText(parent,wx.NewId(),captiontxt,
                                style= wx.LEFT)


        
        sizer.Add(caption,0,wx.ALIGN_LEFT|wx.ALIGN_CENTRE_VERTICAL|wx.RIGHT,5)

        sizer.Add(control,0,wx.ALIGN_LEFT|wx.RIGHT,20)
        return sizer
    
class CaptionCtrl(wx.PyControl):

    def __init__(self, parent, Control, captxt= 'Caption here',
                 id=wx.ID_ANY, pos=wx.DefaultPosition, size=(160,10), name="CaptionControl", **kwargs):
        
        
        wx.PyControl.__init__(self, parent, id, pos, size,
                              style= wx.NO_BORDER|
                              wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN,
                              validator= wx.DefaultValidator, 
                              name=name)
        
        self._bestsize = wx.Size(-999, -999)
        self._ControlClass = Control
        self._captxt = captxt
        
        self.SetLabel(name)
        self.SetBackgroundColour(parent.GetBackgroundColour())
        self.SetForegroundColour(parent.GetForegroundColour())
        
        width = size[0]
        height = size[1]
        
        best_size = self.DoGetBestSize()
        
        if width == -1:
            width = best_size.GetWidth()
        if height == -1:
            height = best_size.GetHeight()
            
        
        #self.control.SetEventHandler(self)
        self.caption = wx.StaticText(self,wx.ID_ANY,captxt
                                     , size=(width,-1 )
                                     , style=wx.LEFT)
        self.control = Control(self
                               ,size=(width,height - self.caption.GetSize().GetHeight())
                               , **kwargs )

        self.SetBestSize((width, height))
        
        
       
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.sizer.Add(self.caption,0)
        self.sizer.Add(self.control,0)
        
        self.SetSizer(self.sizer)
        self.sizer.Layout()
        #self.Fit()
        
        def DoGetBestSize(self):
            """ Calculates The Best Size For Control. """
            control = self._ControlClass(self,-1).GetBestSize()
            szControl = control.GetBestSize()
            caption = wx.StaticText(self,-1,self._captxt).GetBestSize()
            szCaption = caption.GetBestSize()
            self._bestsize.SetWidth( max(szControl.GetWidth(),szCaption.GetWidth()) )
            self._bestsize.SetHeight( szControl.GetHeight() + szCaption.GetHeight() )
            
            
            # oops something went wrong, set to reasonable value
#            if self._bestsize.GetWidth() < 20:
#                self._bestsize.SetWidth(100)
#            if self._bestsize.GetHeight() < 10:
#                self._spinctrl_bestsize.SetHeight(22)
            
            control.Destroy()
            caption.Destroy()
            

            return self._bestsize
        

class CollapsibleTextCtrl(wx.CollapsiblePane):    
    def __init__(self,parent,label="Label here",size=wx.DefaultSize
                 , style= wx.CP_DEFAULT_STYLE |wx.CP_NO_TLW_RESIZE
                 ,txtstyle = 0
                 ,txtsize = wx.DefaultSize
                 ):
        wx.CollapsiblePane.__init__(self,parent,label=label,style=style,size=size)
        self._parent = parent

        self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnPaneChanged, self)
        
        pane = self.GetPane()
        self.txtctrl = wx.TextCtrl(pane, -1, "", size = txtsize, style=txtstyle )
        
    def OnPaneChanged(self, evt=None):
        
        # redo the layout
        self.Layout()
        self._parent.SendSizeEvent()
        
        # and also change the labels
        #if self.IsExpanded():
        #    self.SetLabel("Mask")
        #else:
        #    self.SetLabel("Mask")


class SliceDialog(wx.Dialog):
    def __init__(
            self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False
            , data=None            
            ):
        
        self.data = data
        self.slicedmat = None
        


        # Instead of calling wx.Dialog.__init__ we precreate the dialog
        # so we can set an extra style that must be set before
        # creation, and then we create the GUI object using the Create
        # method.
        pre = wx.PreDialog()
        pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
        pre.Create(parent, ID, title, pos, size, style)

        # This next step is the most important, it turns this Python
        # object into the real wrapper of the dialog (instead of pre)
        # as far as the wxPython extension is concerned.
        self.PostCreate(pre)

        # This extra style can be set after the UI object has been created.
        if 'wxMac' in wx.PlatformInfo and useMetal:
            self.SetExtraStyle(wx.DIALOG_EX_METAL)
            
        # Now continue with the normal construction of the dialog
        # contents
        sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.input = CaptionCtrl(self,wx.Choice, captxt="Input variable:"
                                , size=(100,45)
                                , choices = self.data.inputs
                                )
        
        sizer.Add(self.input,0,wx.ALIGN_CENTRE|wx.ALL, 5)
        self.Bind(wx.EVT_CHOICE, self._OnInputChange, self.input.control)
        self.slice = CaptionCtrl(self,wx.ListBox, captxt="Slices:"
                                , size=(100,350)
                                #, choices = ""
                                , style = wx.LB_SINGLE
                                )
        sizer.Add(self.slice,0,wx.ALIGN_CENTRE|wx.ALL, 5)
        
        self.input.control.Select(0)
        self._OnInputChange()
        
        line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
        sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)

        btnsizer = wx.StdDialogButtonSizer()
        
        if wx.Platform != "__WXMSW__":
            btn = wx.ContextHelpButton(self)
            btnsizer.AddButton(btn)
        
        btnOK = wx.Button(self, wx.ID_OK)
        btnOK.SetHelpText("The OK button completes the dialog")
        btnOK.SetDefault()
        btnsizer.AddButton(btnOK)
        self.Bind(wx.EVT_BUTTON,self._OnOK,btnOK)


        btn = wx.Button(self, wx.ID_CANCEL)
        btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
        btnsizer.AddButton(btn)
        btnsizer.Realize()

        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)

        self.SetSizer(sizer)
        sizer.Fit(self)
        
        
    def _OnOK(self,event=None):
        self._Slice()
        #self.Hide()
        self.EndModal(wx.ID_OK)
        
    def _OnInputChange(self,event=None):
        s = self.input.control.GetSelection()
        print s
        choices = set(self.data.inputmat[s])
        choices = [i for i in choices ]
        choices = sort(choices)
        choices = [str(i) for i in choices]
        self.slice.control.Set(choices)
        
    def _Slice(self):
        input = self.input.control.GetSelection()
        clb = self.slice.control
        s = clb.GetSelection()
        #print 'selections: ',s
        if s == -1:
            self.slicedmat = self.data.outputmat
            self.slicerange = []
            return
            
       
        slice =  float( clb.GetString(s) )
            
        combis = []
        for i,val in enumerate(self.data.inputmat[input]):
            if val == slice:
                combis += [i,]
        #print combis
        self.slicerange = [min(combis),max(combis)]
        self.slicedmat = self.data.outputmat[...,min(combis):max(combis),...,...]
        
        #print self.slicedmat.shape
        
from wx.lib.filebrowsebutton import FileBrowseButton
class _FileBrowseButton(FileBrowseButton):
        
    def OnBrowse (self, event = None):
        """ Going to browse for file... """
        current = self.GetValue()

        directory = os.getcwd()#self.startDirectory# os.path.split(current)
        #print "ddddd", directory
        #if os.path.isdir( current):
        #    directory = current
        #    current = ''
        #elif directory and os.path.isdir( directory[0] ):
        #    current = directory[1]
        #    directory = directory [0]
        #else:
        #    directory = self.startDirectory
        #    current = ''
        dlg = wx.FileDialog(self, self.dialogTitle, directory, current,
                            self.fileMask, self.fileMode)

        if dlg.ShowModal() == wx.ID_OK:
            if dlg.HasFlag(wx.FD_MULTIPLE):
                self.Paths = dlg.GetPaths()
                self.SetValue(str(dlg.GetFilenames())[1:-2])
            else:
                self.Paths = [dlg.GetPath(),]
                self.SetValue(dlg.GetPath())
        
        dlg.Destroy()
